package com.iflytek.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WordCound1 {
    public static void main(String[] args) throws Exception {
        //创建Flink环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //2、读取外部文件
        DataSource<String> textFile = env.readTextFile("data/words.txt");
        //3、转换数据格式
        FlatMapOperator<String, Tuple2<String, Long>> danci = textFile.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1L));
                }
            }
        });
        //4、按照单词进行分组
        UnsortedGrouping<Tuple2<String, Long>> dancigb = danci.groupBy(0);
        //5、分组内聚合统计
        AggregateOperator<Tuple2<String, Long>> sum = dancigb.sum(1);
        //6、打印结果
        sum.print();

    }
}
